package com.act;

import java.util.ArrayList;
import java.util.Date;

import org.apache.http.Header;
import org.apache.http.message.BasicNameValuePair;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.Html;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.ScrollView;
import android.widget.TextView;

import com.adapter.AnswerAdapter;
import com.bean.Answer;
import com.bean.BaseBean;
import com.bean.QuestionDetail;
import com.bean.UserInfo;
import com.common.Constant;
import com.common.TextHttpResponseHandler;
import com.control.UserControl;
import com.easemob.util.DateUtils;
import com.xike.imageloader.core.ImageLoader;
import com.xike.kyt.R;
import com.xike.util.MyUtil;

public class Question_DetailAct extends BaseAct implements OnClickListener {

	private static final int REQUEST_CODE_TO_ANSWER = 1;
	private static final int REQUEST_CODE_TO_LOGIN = 2;
	private static final int REQUEST_CODE_TO_ANSWER_DETAIL = 3;

	TextView tv_back, head_tv_answer, tv_answer, tv_focus, tv_answerNum;

	RelativeLayout layout_userInfo;
	TextView tv_userName, tv_createTime;
	TextView tv_title, tv_summary;
	ImageView img_userImage;
	ScrollView layout_content;

	ListView lv_answers;
	AnswerAdapter adapter;
	ArrayList<Answer> answers = new ArrayList<Answer>();

	QuestionDetail questionDetail;

	long questionId;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.act_question_detail);
		Bundle bundle = getIntent().getExtras();
		if (bundle != null && bundle.containsKey("questionId")) {
			questionId = bundle.getLong("questionId");
		}
		initViews();

	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		if (requestCode == REQUEST_CODE_TO_ANSWER && resultCode > 0) {// 回答成功，回来刷新；
			serviceGetDetail();
		} else if (requestCode == REQUEST_CODE_TO_LOGIN && resultCode > 0) {
			serviceGetDetail();
		} else if (requestCode == REQUEST_CODE_TO_ANSWER_DETAIL && resultCode > 0) {
			serviceGetDetail();
		}
	}

	@Override
	protected void initViews() {
		tv_back = (TextView) findViewById(R.id.headTitle_tv_back);

		layout_content = (ScrollView) findViewById(R.id.questionDetail_layout_content);

		head_tv_answer = (TextView) findViewById(R.id.questionDetail_headTitle_answer);
		tv_answer = (TextView) findViewById(R.id.questionDetail_tv_answer);
		tv_answerNum = (TextView) findViewById(R.id.questionDetail_tv_answerNum);
		tv_focus = (TextView) findViewById(R.id.questionDetail_tv_focus);
		tv_summary = (TextView) findViewById(R.id.questionDetail_tv_questionSummary);
		tv_title = (TextView) findViewById(R.id.questionDetail_tv_questionTitle);

		layout_userInfo = (RelativeLayout) findViewById(R.id.questionDetail_layout_user);
		layout_userInfo.setOnClickListener(this);
		tv_userName = (TextView) findViewById(R.id.user_tv_name);
		tv_createTime = (TextView) findViewById(R.id.user_tv_desc);
		img_userImage = (ImageView) findViewById(R.id.user_img_image);

		lv_answers = (ListView) findViewById(R.id.questionDetail_listView);

		tv_back.setOnClickListener(this);
		tv_answer.setOnClickListener(this);
		head_tv_answer.setOnClickListener(this);
		tv_focus.setOnClickListener(this);

		adapter = new AnswerAdapter(this, answers);
		lv_answers.setAdapter(adapter);

		lv_answers.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				Answer answer = answers.get(position - 1);
				Intent it = new Intent(Question_DetailAct.this, Answer_DetailAct.class);
				it.putExtra("answerId", answer.getId());
				startActivityForResult(it, REQUEST_CODE_TO_ANSWER_DETAIL);
			}
		});
		serviceGetDetail();
	}

	@Override
	protected void updateViews() {

		long createTime = questionDetail.getCreate_time();
		ArrayList<Answer> resultAnswers = questionDetail.getAnswers();

		UserInfo user = questionDetail.getUser();
		BitmapDrawable bd = (BitmapDrawable) getResources().getDrawable(R.drawable.default_user_avator);
		MyUtil.displayImageView(this, user.getAvator(), img_userImage, bd.getBitmap(), true);
		MyUtil.setTextViewText(tv_userName, user.getShow_name(), 0, "未知用户");

		MyUtil.setTextViewText(tv_createTime, DateUtils.getTimestampString(new Date(createTime)), View.INVISIBLE, "");
		MyUtil.setTextViewText(tv_title, questionDetail.getTitle(), View.GONE, "");

		tv_focus.setText(questionDetail.isIs_focus() ? "已关注" : "关注问题");

		final Html.ImageGetter imageGetter = new Html.ImageGetter() {

			public Drawable getDrawable(String source) {
				Drawable drawable = null;
				try {
					Bitmap bitmap = ImageLoader.getInstance().loadImageSync(source);
					drawable = new BitmapDrawable(bitmap);
				} catch (Exception e) {
					e.printStackTrace();
					return null;
				}
				drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
				return drawable;
			};
		};
		tv_summary.setText(Html.fromHtml(questionDetail.getDescription(), imageGetter, null));

		if (resultAnswers == null || resultAnswers.size() <= 0) {
			tv_answerNum.setText("暂无相关回答");
		} else {
			answers.clear();
			tv_answerNum.setText(resultAnswers.size() + " 个答案");
			answers.addAll(resultAnswers);
			adapter.notifyDataSetChanged();
			MyUtil.setListViewHeightBasedOnChildren(lv_answers);
		}
		layout_content.smoothScrollTo(0, 20);
	}

	private void serviceGetDetail() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(questionId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_QUESTION_DETAIL, params);
		// // 本地缓存
		// if (LocalFileHelper.getInstance(this).fileIsExited(strUrl)) {
		// QuestionDetail result = gson.fromJson(LocalFileHelper.getContentFromFile(strUrl), QuestionDetail.class);
		// dealRequestResult(result);
		// return;
		// }

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				QuestionDetail result = gson.fromJson(responseString, QuestionDetail.class);
				dealRequestResult(result);
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Question_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void dealRequestResult(QuestionDetail result) {
		if (result != null) {
			if (result.isReturnTrue()) {
				questionDetail = result;
				updateViews();
			} else {
				mToast.showToast(this, result.getError_description());
			}
		} else {
			mToast.showToast(this, getString(R.string.net_error));
		}
	}

	private void serviceFocusQuestion() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(questionId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_QUESTION_FOCUS, params);

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Question_DetailAct.this, "已关注");
					tv_focus.setText("已关注");
				} else {
					mToast.showToast(Question_DetailAct.this, getResources().getString(R.string.net_error));
				}
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Question_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	private void serviceCancelFocusQuestion() {
		ArrayList<BasicNameValuePair> params = new ArrayList<BasicNameValuePair>();
		params.add(new BasicNameValuePair("id", String.valueOf(questionId)));

		String strUrl = MyUtil.signRequestUrl(Constant.SERVER_URL_QUESTION_FOCUS_CANCEL, params);

		client.get(this, strUrl, new TextHttpResponseHandler(this) {

			@Override
			public void onSuccess(int statusCode, Header[] headers, String responseString) {
				BaseBean result = gson.fromJson(responseString, BaseBean.class);
				if (result != null && result.isReturnTrue()) {
					mToast.showToast(Question_DetailAct.this, "取消关注");
					tv_focus.setText("关注问题");
				} else {
					mToast.showToast(Question_DetailAct.this, getResources().getString(R.string.net_error));
				}
				super.onSuccess(statusCode, headers, responseString);
			}

			@Override
			public void onFailure(int statusCode, Header[] headers, String responseString, Throwable throwable) {
				mToast.showToast(Question_DetailAct.this, getResources().getString(R.string.net_error));
				super.onFailure(statusCode, headers, responseString, throwable);
			}
		});
	}

	@Override
	public void onClick(View v) {
		Intent it_anwer;
		switch (v.getId()) {
		case R.id.headTitle_tv_back:
			finish();
			break;
		case R.id.questionDetail_layout_user:
			intentToUserInfoAct();
			break;
		case R.id.questionDetail_tv_answer:
			if (UserControl.isLogined()) {
				it_anwer = new Intent(Question_DetailAct.this, AnswerAct.class);
				it_anwer.putExtra("questionId", questionId);
				it_anwer.putExtra("questionTitle", questionDetail.getTitle());
				startActivityForResult(it_anwer, REQUEST_CODE_TO_ANSWER);
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		case R.id.questionDetail_headTitle_answer:
			if (UserControl.isLogined()) {
				it_anwer = new Intent(Question_DetailAct.this, AnswerAct.class);
				it_anwer.putExtra("questionId", questionId);
				it_anwer.putExtra("questionTitle", questionDetail.getTitle());
				startActivityForResult(it_anwer, REQUEST_CODE_TO_ANSWER);
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		case R.id.questionDetail_tv_focus:
			if (UserControl.isLogined()) {
				if (tv_focus.getText().toString().equals("已关注")) {
					serviceCancelFocusQuestion();
				} else {
					serviceFocusQuestion();
				}
			} else {
				MyUtil.intentToLogin(this, REQUEST_CODE_TO_LOGIN);
			}

			break;
		default:
			break;
		}
	}

	private void intentToUserInfoAct() {
		if (questionDetail == null) {
			return;
		}
		UserInfo user = questionDetail.getUser();
		if (user == null) {
			return;
		}
		Intent it_userInfo = new Intent(this, UserInfoAct.class);
		it_userInfo.putExtra("userId", user.getId());
		startActivity(it_userInfo);
	}
}
